package com.emm.yixun.website.controller.deal;
//框架包
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.emm.yixun.common.model.Dictionary;
import com.emm.yixun.common.model.Image;
import com.emm.yixun.common.model.MortgageRecordFollow;
//变化的引用
import com.emm.yixun.common.model.PriceScheme;
import com.emm.yixun.common.model.TreeNode;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.DictionaryDto;
import com.emm.yixun.common.model.dto.ImageDto;
import com.emm.yixun.common.model.dto.MortgageRecordDto;
import com.emm.yixun.common.model.dto.MortgageRecordFollowDto;
import com.emm.yixun.common.model.dto.ProjectDto;
import com.emm.yixun.common.model.dto.UserDto;
import com.emm.yixun.common.model.enums.ContactTypeEnum;
import com.emm.yixun.common.model.enums.HousingFundTypeEnum;
import com.emm.yixun.common.model.enums.ImgTypeEnum;
import com.emm.yixun.common.model.enums.PaymentMethodEnum;
import com.emm.yixun.common.model.enums.ProgressLoanEnum;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.page.PageUtil;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.estate.service.ProjectTreeServiceFacade;
import com.emm.yixun.marketing.service.MortgageRecordFollowServiceFacade;
import com.emm.yixun.marketing.service.MortgageRecordServiceFacade;
import com.emm.yixun.system.service.DictionaryServiceFacade;
import com.emm.yixun.system.service.ImageServiceFacade;
import com.emm.yixun.system.service.UserServiceFacade;
import com.emm.yixun.website.common.utils.base.Const;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.controller.base.BaseController;
import com.emm.yixun.website.vo.common.ExtResultVo;
//common
//website
@Controller
@RequestMapping("/deal/mortgage/")
public class MortgageController extends BaseController<PriceScheme>{
	
	@Autowired
	private MortgageRecordServiceFacade mortgageRecordServiceFacade;
	@Autowired
	private MortgageRecordFollowServiceFacade mortgageRecordFollowServiceFacade;
	@Autowired
	private DictionaryServiceFacade dictionaryServiceFacade;
	@Autowired
	private UserServiceFacade userServiceFacade;
	@Autowired
	private ImageServiceFacade imageServiceFacade;
	@Autowired
	private ProjectTreeServiceFacade projectTreeServiceFacade;

	@RequestMapping(value="index")
	public String index(ModelMap map, HttpServletRequest request){
		if(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"deal:mortgage:list")){
			//查询菜单按钮权限
			map.put("permitBtn",getPermissionBtnArray());		
			map.put("menu",request.getParameter("menu"));		
			return "/deal/mortgage/index";
		}
		return Const.NO_AUTHORIZED_URL;
	}
	
	@RequestMapping(value="mortgageDetail")
	public String mortgageDetail(ModelMap map, MortgageRecordDto dto,HttpServletRequest request){
			//查询菜单按钮权限
			//map.put("permitBtn", getPermitBtn(Const.RESOURCES_TYPE_FUNCTION));
			map.put("id", dto.getId());
			map.put("changeType", request.getParameter("changeType"));
			return "/deal/mortgage/detail";
	}
	
	/**
	 * 按揭列表
	 * @param dto
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="mortgageList")
	@ResponseBody
    public Page<MortgageRecordDto> mortgageList(MortgageRecordDto dto, HttpServletRequest request, HttpServletResponse response, Integer limit,Integer page){
		try {
			if(dto.getExt_signedDateAfter()!=null&&!dto.getExt_signedDateAfter().equals("")){
				dto.setExt_signedDateAfter(dto.getExt_signedDateAfter()+" 23:59:59");
			}
			if(dto.getExt_statementDateAfter()!=null&&!dto.getExt_statementDateAfter().equals("")){
				dto.setExt_statementDateAfter(dto.getExt_statementDateAfter()+" 23:59:59");
			}
			dto.setOrders(" t.create_time desc ");
    		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    		if(StringUtils.isNotEmpty(dto.getExt_signedDateBefore())){
    			dto.setSignedDateBefore(sdf.parse(dto.getExt_signedDateBefore()));
    		}
			if(StringUtils.isNotEmpty(dto.getExt_signedDateAfter())){
    			dto.setSignedDateAfter(sdf.parse(dto.getExt_signedDateAfter()));
    		}
			if(StringUtils.isNotEmpty(dto.getExt_statementDateBefore())){
				dto.setStatementDateBefore(sdf.parse(dto.getExt_statementDateBefore()));
			}
			if(StringUtils.isNotEmpty(dto.getExt_statementDateAfter())){
				dto.setStatementDateBefore(sdf.parse(dto.getExt_statementDateAfter()));
			}
			if(StringUtils.isNotBlank(dto.getMortgageReceivedStatus())){
				if(dto.getMortgageReceivedStatus().indexOf(",")!=-1){
					List<String> list=new ArrayList<String>();
        			Collections.addAll(list, dto.getMortgageReceivedStatus().split(","));
					dto.setMortgageReceivedStatusList(list);
					dto.setMortgageReceivedStatus(null);
				}
			}
			if(StringUtils.isNotBlank(dto.getMortgageCheckStatus())){
				if(dto.getMortgageCheckStatus().indexOf(",")!=-1){
					List<String> list=new ArrayList<String>();
        			Collections.addAll(list, dto.getMortgageCheckStatus().split(","));
					dto.setMortgageCheckStatusList(list);
					dto.setMortgageCheckStatus(null);
				}
			}
			if(StringUtils.isNotEmpty(dto.getTreeId())){
				String treeId = dto.getTreeId();
    			if(treeId.indexOf("PROJECT_") == 0){
    				dto.setProjectId(Long.parseLong(treeId.substring(treeId.indexOf("_")+1)));
    			}else if(treeId.indexOf("PREMISES_") == 0){
    				dto.setPremisesId(Long.parseLong(treeId.substring(treeId.indexOf("_")+1)));
    			}else if(treeId.indexOf("BUILDING_") == 0){
    				dto.setBuildingId(Long.parseLong(treeId.substring(treeId.indexOf("_")+1)));
    			}else if(treeId.indexOf("UNIT_") == 0){
    				dto.setUnitId(Long.parseLong(treeId.substring(treeId.indexOf("_")+1)));
    			}else if(treeId.indexOf("ROOM_") == 0){
    				dto.setRoomId(Long.parseLong(treeId.substring(treeId.indexOf("_")+1)));
    			}else if(treeId.indexOf("CARAREA_") == 0){
    				
    			}else if(treeId.indexOf("CARPORT_") == 0){
    				
    			}
    		}
			
			User user = ShiroUtil.getCurrentUser();
			dto.setPermissionUserId(user.getId());
			//项目数据权限资源缓存
			String resourcesCode = ShiroUtil.getDataPermissionResources(dto.getResourcesName());
			if(null == dto.getResourcesCode() || "".equals(dto.getResourcesCode())){
				dto.setResourcesCode(resourcesCode);
			}else if("".equals(resourcesCode)){
				ShiroUtil.setDataPermissionResources(dto.getResourcesName(), dto.getResourcesCode());
			}
			dto.setMerchantId(user.getMerchantId());
    		Page<MortgageRecordDto> resPage = mortgageRecordServiceFacade.findPageDtoByDto(dto, PageUtil.begin(page, limit), limit);
            if(resPage.getSuccess()){
            	if(null==resPage.getRows()){
            		resPage.setRows(new ArrayList<MortgageRecordDto>());
            	}else{
            		List<MortgageRecordDto> resList = resPage.getRows();
            		DictionaryDto dicDto = new DictionaryDto();
            		dicDto.setDictionaryType("BK");
            		ResponseList<Dictionary> dicRes = dictionaryServiceFacade.findByDto(dicDto);
            		List<Dictionary> dicList = dicRes.getEntity();
            		for(MortgageRecordDto mortRecDto: resList){
            			if(StringUtils.isNotEmpty(mortRecDto.getPaymentMethod())){
            				mortRecDto.setPaymentMethod(PaymentMethodEnum.getByNo(mortRecDto.getPaymentMethod()).getDes());
            			}
            			if(StringUtils.isNotEmpty(mortRecDto.getHousingFundType())){
            				mortRecDto.setHousingFundType(HousingFundTypeEnum.getByNo(mortRecDto.getHousingFundType()).getDes());
            			}
            			if(StringUtils.isNotEmpty(mortRecDto.getContactType())){
            				mortRecDto.setContactType(ContactTypeEnum.getByNo(mortRecDto.getContactType()).getDes());
            				
            			}
            			if(StringUtils.isNotEmpty(mortRecDto.getProgressLoan())){
            				mortRecDto.setProgressLoan(ProgressLoanEnum.getByNo(mortRecDto.getProgressLoan()).getDes());
            			}
            			
            			//已收金额占比: 已收金额/合同金额
            			BigDecimal signAmount =  mortRecDto.getSignAmount();
            			BigDecimal receivedAmount =  mortRecDto.getHrrReceived()==null?(new BigDecimal(0)):(new BigDecimal(mortRecDto.getHrrReceived()));
            			BigDecimal decProportionValue = new BigDecimal(0);
            			if(signAmount.compareTo(new BigDecimal(0)) != 0){
            				decProportionValue = receivedAmount.divide(signAmount, 10, RoundingMode.HALF_DOWN);
            			}
            			DecimalFormat df = new DecimalFormat("#.00");
            			mortRecDto.setProportionValue(new BigDecimal(df.format(decProportionValue)).multiply(new BigDecimal(100)));
            			//银行名称
            			if(null != mortRecDto.getBankId()){
            				if(null != dicList){
            					for(Dictionary dic: dicList){
            						if(dic.getId().compareTo(mortRecDto.getBankId())==0){
            							mortRecDto.setBankName(dic.getDictionaryName());
            							break;
            						}
            					}
            				}
            			}
            			//是否逾期未放款
            			//逾期天数
            			if(mortRecDto.getExpectLoadDate() != null){
            				int dayNum = getDayNum(new Date(), mortRecDto.getExpectLoadDate());
            				if(dayNum > 0 && !ProgressLoanEnum.PL_8.getDes().equals(mortRecDto.getProgressLoan())){
            					mortRecDto.setIsOverdueLenders("是");
            					mortRecDto.setOverdueDayNum(String.valueOf(dayNum));
            				}else{
            					mortRecDto.setIsOverdueLenders("否");
            					/*mortRecDto.setOverdueDayNum(null);*/
            				}
            			}
            		}
            	}
            	resPage.setPageNumber(page);
            	return resPage;
            }
		} catch (Exception e) {
			logger.error(e.toString(),e);
		}
    	return new Page<MortgageRecordDto>();
    }
	
	/**
	 * 进入认筹收款界面
	 * @return
	 */
	@RequestMapping("getMortgageRecordById")
	public void getMortgageRecordById(MortgageRecordDto dto, HttpServletRequest request, HttpServletResponse response) {
		try {
			ExtResultVo extResultVo = new ExtResultVo();
			extResultVo.setSuccess(false);
			if(dto.getId() == null){
				extResultVo.setErrorMessage("未找到按揭记录");
			}else{
				//认筹信息
				Response<MortgageRecordDto> resMortgageRecord = mortgageRecordServiceFacade.findMortgageDetail(dto);
				MortgageRecordDto mortgageRecordDto = resMortgageRecord.getEntity();
				if(mortgageRecordDto != null){
					extResultVo.setSuccess(true);
					if(StringUtils.isNotEmpty(mortgageRecordDto.getPaymentMethod())){
						mortgageRecordDto.setPaymentMethod(PaymentMethodEnum.getByNo(mortgageRecordDto.getPaymentMethod()).getDes());
        			}
					
					//查询已上传的附件
					ImageDto imageDto = new ImageDto();
					imageDto.setObjectId(mortgageRecordDto.getId());
					imageDto.setImgType(ImgTypeEnum.MORTGAGE.getNo());
					ResponseList<Image> resImage = imageServiceFacade.findByDto(imageDto);
					if(resImage.isSuccess()){
						List<Image> imageList = resImage.getEntity();
						if(null != imageList && imageList.size() > 0){
							String fileArr[] = new String[imageList.size()];
							for(int ii=0; ii<imageList.size(); ii++){
								Image image = imageList.get(ii);
								fileArr[ii] = image.getSmallUrl();
							}
							mortgageRecordDto.setFileList(fileArr);
						}
					}
					
					extResultVo.setData(mortgageRecordDto);
				}else{
					extResultVo.setErrorMessage("未找到按揭记录");
				}
			}
			resultJson(response, extResultVo);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 按揭跟进记录列表
	 * @param dto
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="mortgageFollowList")
	@ResponseBody
    public Page<MortgageRecordFollow> mortgageFollowList(MortgageRecordFollowDto dto, HttpServletRequest request, HttpServletResponse response, Integer limit,Integer page){
		if(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"deal:mortgage:followList")){
			try {
	    		Page<MortgageRecordFollow> resPage = mortgageRecordFollowServiceFacade.findPageByDto(dto, PageUtil.begin(page, limit), limit);
	            if(resPage.getSuccess()){
	            	if(null==resPage.getRows()){
	            		resPage.setRows(new ArrayList<MortgageRecordFollow>());
	            	}else{
	            		UserDto userDto = new UserDto();
	            		ResponseList<User> resUserList = userServiceFacade.findByDto(userDto);
	            		List<User> userList = resUserList.getEntity();
	            		List<MortgageRecordFollow> mrfList = resPage.getRows();
	            		if(null != mrfList){
	            			for(MortgageRecordFollow mrf: mrfList){
	            				if(StringUtils.isNotEmpty(mrf.getOldProgressLoan())){
	            					mrf.setOldProgressLoan(ProgressLoanEnum.getByNo(mrf.getOldProgressLoan()).getDes());
	            				}
	            				if(StringUtils.isNotEmpty(mrf.getNowProgressLoan())){
	            					mrf.setNowProgressLoan(ProgressLoanEnum.getByNo(mrf.getNowProgressLoan()).getDes());
	            				}
	            				if(null != userList){
	            					for(User user: userList){
	            						if(user.getId().equals(mrf.getCreateUserId())){
	            							//将userCode用作用户名...
	            							//此列表只作展示用,用不到userCode
	            							mrf.setUserCode(user.getUserName());
	            							break;
	            						}
	            					}
	            					
	            				}
	            			}
	            		}
	            		resPage.setRows(mrfList);
	            	}
	            	resPage.setPageNumber(limit);
	            	return resPage;
	            }
			} catch (Exception e) {
				logger.error(e.toString(),e);
			}
		}
	
    	return new Page<MortgageRecordFollow>();
    }
	
	/**
	 * 添加按揭跟进记录
	 * @param dto
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="addMortgageFollow")
	@ResponseBody
    public void addMortgageFollow(MortgageRecordDto dto, HttpServletRequest request, HttpServletResponse response){
		ExtResultVo extResultVo = new ExtResultVo();
		Map<String, String> returnMap = new HashMap<String, String>();
		try {
			User user = ShiroUtil.getCurrentUser();
			dto.setUserId(user.getId());
			dto.setUserCode(user.getUserCode());
			returnMap = mortgageRecordServiceFacade.addMortgageFollow(dto);
			if("00000".equals(returnMap.get("returnCode"))){
				extResultVo.setSuccess(false);
			}else if("00001".equals(returnMap.get("returnCode"))){
				extResultVo.setSuccess(true);
			}
			extResultVo.setErrorMessage(returnMap.get("returnMsg"));
			resultJson(response, extResultVo);
		} catch (Exception e) {
			logger.error("按揭变更错误");
			e.printStackTrace();
			try {
				extResultVo.setErrorMessage(e.getMessage());
				resultJson(response, extResultVo);
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
    }
	
	/**
	* 方法描述 : 房产树
	* @return List<TreeNode>
	 */
	@RequestMapping(value = "treeNodeList")
	public @ResponseBody List<TreeNode> treeNodeList(ProjectDto projectDto){
		User user = ShiroUtil.getCurrentUser();
		projectDto.setPermissionUserId(user.getId());
		//项目数据权限资源缓存
		String resourcesCode = ShiroUtil.getDataPermissionResources(projectDto.getResourcesName());
		if(null == projectDto.getResourcesCode() || "".equals(projectDto.getResourcesCode())){
			projectDto.setResourcesCode(resourcesCode);
		}else if("".equals(resourcesCode)){
			ShiroUtil.setDataPermissionResources(projectDto.getResourcesName(), projectDto.getResourcesCode());
		}
		projectDto.setMerchantId(user.getMerchantId());
		ResponseList<TreeNode> treeNode= projectTreeServiceFacade.treeNodeList(projectDto);
		return treeNode.getEntity();
		
	}
	
	public int getDayNum(Date nowTime, Date busTime) throws ParseException{
		//时间转换类
        SimpleDateFormat sdf_day = new SimpleDateFormat("yyyy-MM-dd");
        Date date1 = sdf_day.parse(sdf_day.format(nowTime));
        Date date2 = sdf_day.parse(sdf_day.format(busTime));
        long diff = date1.getTime() - date2.getTime();//这样得到的差值是微秒级别  
        long days = diff / (1000 * 60 * 60 * 24);  
        int dayNum = Integer.parseInt(String.valueOf(days));
        return dayNum;
	}
	
	public static void main(String[] args) {
		String aaa = "PROJECT_12";
		System.out.println(aaa.indexOf("PROJECT_"));
		System.out.println(aaa.substring(aaa.indexOf("_")+2));
	}
}
